﻿//Código desenvolvido na integra por João Ribeiro
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlServerCe;
using System.Configuration;
using System.Data.SqlClient;
using System.Web.Security;

namespace GestaoContas
{
    public partial class PesquisaContas : Form
    {
        private string _tipoUser;
        private string _connectionStringLogin;
        private string _connectionStringJardimBD;
        private int _selectedRow = 0;
        private ContaDeUtilizador _contaUtilizador;

        public PesquisaContas()
        {
            InitializeComponent();
            _connectionStringLogin = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
            _connectionStringJardimBD = ConfigurationManager.ConnectionStrings["ConnectionStringJardimBD"].ConnectionString;
        }

        public PesquisaContas(string tipoUser)
        {
            InitializeComponent();
            _connectionStringLogin = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
            _connectionStringJardimBD = ConfigurationManager.ConnectionStrings["ConnectionStringJardimBD"].ConnectionString;
            this.dataGridViewPesquisaContas.MouseDown += new System.Windows.Forms.MouseEventHandler(this.dataGridViewPesquisaContas_MouseDown);

            _tipoUser = tipoUser;
            if (tipoUser == "Funcionario")
            {
                verContaToolStripMenuItem.Enabled = true;
                alterarContaToolStripMenuItem.Enabled = false;
            }
            PreencheComboBoxTipoConta();
        }


        /// <summary>
        /// Preenche a gridview com os dados dos utilizadores consoante as suas roles.
        /// </summary>
        /// <param name="role"></param>
        private void PreencheGridView(string role)
        {
            string query = @"SELECT Nome, Telefone, Telemovel as ""Telemóvel"", NumeroContribuinte as ""Nº de contribuinte"", email as ""E-mail"" FROM Pessoa WHERE Role = '" + role +"'"; 

            try
            {
                SqlCeConnection conn = new SqlCeConnection(_connectionStringJardimBD);
                SqlCeCommand cmd = new SqlCeCommand(query, conn);

                SqlCeDataAdapter da = new SqlCeDataAdapter();
                DataSet ds = new DataSet();

                da.SelectCommand = cmd;

                da.Fill(ds);
                dataGridViewPesquisaContas.DataSource = ds.Tables[0];
                dataGridViewPesquisaContas.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        /// <summary>
        /// Preenche a combobox do tipo de conta com os dados da tabela aspnet_Roles
        /// </summary>
        private void PreencheComboBoxTipoConta()
        {
            try
            {
                string query = @"SELECT RoleName FROM aspnet_Roles";
                SqlConnection conn = new SqlConnection(_connectionStringLogin);

                SqlCommand cmd = new SqlCommand(query, conn);

                SqlDataAdapter da = new SqlDataAdapter();
                DataSet ds = new DataSet();
                da.SelectCommand = cmd;

                da.Fill(ds);

                comboBoxTipoDeContas.DisplayMember = "RoleName";
                comboBoxTipoDeContas.ValueMember = "RoleName";
                comboBoxTipoDeContas.DataSource = ds.Tables[0];
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
        }

        private void comboBoxTipoDeContas_SelectedIndexChanged(object sender, EventArgs e)
        {
            PreencheGridView(comboBoxTipoDeContas.Text);
        }

        private void dataGridViewPesquisaContas_Click(object sender, EventArgs e)
        {
            PreencheGridView(comboBoxTipoDeContas.Text);
        }

        private void dataGridViewPesquisaContas_MouseDown(object sender, MouseEventArgs e)
        {
            try
            {
                if (e.Button == MouseButtons.Right && dataGridViewPesquisaContas.RowCount > 0)
                {
                    var hti = dataGridViewPesquisaContas.HitTest(e.X, e.Y);
                    dataGridViewPesquisaContas.ClearSelection();
                    dataGridViewPesquisaContas.Rows[hti.RowIndex].Selected = true;
                    _selectedRow = hti.RowIndex;
                }
            }
            catch (Exception ex) {  }
        }

        private void verContaToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (dataGridViewPesquisaContas.RowCount > 0)
            {
                string nomeQuerySearch = dataGridViewPesquisaContas.Rows[_selectedRow].Cells[0].Value.ToString();
                string contribuinteQuerySearch = dataGridViewPesquisaContas.Rows[_selectedRow].Cells[3].Value.ToString();
                _contaUtilizador = new ContaDeUtilizador();

                VerAlterarConta vac = new VerAlterarConta(true, 1, nomeQuerySearch, contribuinteQuerySearch);
                vac.Text = "Ver conta";
                vac.ShowDialog();
            }
        }

        private void alterarContaToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (dataGridViewPesquisaContas.RowCount > 0)
            {
                bool registoAlterado = false;
                string nomeQuerySearch = dataGridViewPesquisaContas.Rows[_selectedRow].Cells[0].Value.ToString();
                string contribuinteQuerySearch = dataGridViewPesquisaContas.Rows[_selectedRow].Cells[3].Value.ToString();

                ContaDeUtilizador contaAntiga = new ContaDeUtilizador();
                // preenche o objecto com os dados antes de serem alterados.
                contaAntiga.PreencheOjectoContaUtilizador(nomeQuerySearch, contribuinteQuerySearch);
                ContaLogin loginAntigo = new ContaLogin(contaAntiga.UserId, contaAntiga.RoleDoUtilizador, contaAntiga.Email);
                
                VerAlterarConta vac = new VerAlterarConta(false, 1, nomeQuerySearch, contribuinteQuerySearch);
                
                vac.Text = "Alterar conta";
                if (vac.ShowDialog() == DialogResult.OK)
                {
                    ContaDeUtilizador contaAlterada = new ContaDeUtilizador(
                        vac.PessoaId, 
                        vac.Nome, 
                        vac.Morada,
                        vac.Telefone,
                        vac.Telemovel,
                        vac.Contribuinte,
                        vac.Email,
                        vac.UserId,
                        vac.Role);
                    if (!contaAlterada.Igual(contaAntiga))
                    {
                        registoAlterado = contaAlterada.GuardaAlteracaoPessoa();
                    }
                    ContaLogin loginAlterado = new ContaLogin(
                        vac.UserId,
                        vac.UserName,
                        vac.ContaActivada,
                        vac.Role,
                        vac.Email,
                        vac.PassAntiga,
                        vac.Pass,
                        vac.PassConfirma);
                    if (!loginAlterado.Igual(loginAntigo))
                    {
                        registoAlterado = loginAlterado.GravaAlteracoesLogin(loginAntigo);
                    }
                }
                if (registoAlterado)
                {
                    MessageBox.Show("Conta alterada.");
                }
                PreencheGridView(comboBoxTipoDeContas.Text);
            }

        }

        private void verEducandosToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (dataGridViewPesquisaContas.RowCount > 0)
            {
                string nomeQuerySearch = dataGridViewPesquisaContas.Rows[_selectedRow].Cells[0].Value.ToString();
                string contribuinteQuerySearch = dataGridViewPesquisaContas.Rows[_selectedRow].Cells[3].Value.ToString();

                VerAlterarConta vac = new VerAlterarConta(true, 2, nomeQuerySearch, contribuinteQuerySearch);
                vac.Text = "Ver Educando";
                vac.ShowDialog();
            }
        }
    }
}